import State from "../../framework/scripts/state/State"
import PanelStateMachine from "../../scripts/PanelStateMachine"
import StateDef from "./StateDef"


export default class StateUpDown extends State {
    private _player: cc.Node

    private _speed: number = 400
    private _moveUp: boolean = false
    private _moveDown: boolean = false


    public onEnter(_arg?: any, _lastKey?: string): void {
        cc.log('StateUpDown 进入状态 _lastKey:', _lastKey)
        this._player = (this._owner as PanelStateMachine).skin.getChildByName('player')

        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this)
        cc.systemEvent.on(cc.SystemEvent.EventType.KEY_UP, this.onKeyUp, this)
    }

    public onReEnter(_arg?: any): void {
        cc.log('StateUpDown 重新进入状态')
    }

    public onUpdate(dt: number): void {
        if (this._moveUp) {
            this._player.y += this._speed * dt
            const maxY = cc.winSize.height / 2 - this._player.height / 2
            if (this._player.y > maxY) {
                this._player.y = maxY
            }
        } else if (this._moveDown) {
            this._player.y -= this._speed * dt
            const minY = -cc.winSize.height / 2 + this._player.height / 2
            if (this._player.y < minY) {
                this._player.y = minY
            }
        }
    }

    public onExit(_nextKey: string): void {
        cc.log('StateUpDown 退出状态 _nextKey:', _nextKey)
        // cc.systemEvent.off(cc.SystemEvent.EventType.KEY_DOWN, this.onKeyDown, this)
        // cc.systemEvent.off(cc.SystemEvent.EventType.KEY_UP, this.onKeyUp, this)
    }

    public getStateKey(): string {
        return StateDef.upDown
    }


    private onKeyDown(et: cc.Event.EventKeyboard) {
        if (et.keyCode == cc.macro.KEY.w) {
            this._moveUp = true
        } else if (et.keyCode == cc.macro.KEY.s) {
            this._moveDown = true
        }
    }

    private onKeyUp(et: cc.Event.EventKeyboard) {
        if (et.keyCode == cc.macro.KEY.w) {
            this._moveUp = false
        } else if (et.keyCode == cc.macro.KEY.s) {
            this._moveDown = false
        }
    }
}
